package com.yx;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @Classname TestThread
 * @Date 2021/07/22 16:32
 * @Author by yx
 * @Description: 继承Threa
 */
@Slf4j
public class TestThread {

    // 创建一个线程池
    static ExecutorService executorService = Executors.newFixedThreadPool(5);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建一个线程
        MyThread myThread = new MyThread();
        MyRunable myRunable = new MyRunable();

        // 创建带有返回值的线程
        Callable<Integer> myCallable = new MyCallable();
        // 使用FutureTask来包装MyCallable对象
        FutureTask<Integer> futureTask = new FutureTask<>(myCallable);


        // 开启线程
        myThread.start();
        // run()方法被当做main()方法中的一个普通方法执行，失去了线程的意义
        myRunable.run();
        // 开启myRunable线程
        new Thread(myRunable).start();
        // 开启Callable线程
        new Thread(futureTask).start();

        // 获取返回值
        log.debug("Callable'result: {}", futureTask.get());

        // 提交给线程池执行一个任务
        executorService.submit(myRunable);

        executorService.submit(new FutureTask<>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                log.debug("Callable'name: {}", Thread.currentThread().getName());
                int sum = 0;
                for (int i = 0; i < 100; i++) {
                    sum += i;
                }
                return sum;
            }
        }));
    }
}

@Slf4j
class MyThread extends Thread {

    @Override
    public void run() {
        log.debug("Thread'name: {}", Thread.currentThread().getName());
    }
}

@Slf4j
class MyRunable implements Runnable {

    @Override
    public void run() {
        log.debug("Runable'name: {}", Thread.currentThread().getName());
    }
}

/**
 * @Author:yx
 * @return 返回泛型类型的值
 * @Date 2021/07/22 16:46
 * @Description: 带返回值的线程
 **/
@Slf4j
class MyCallable implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        log.debug("Callable'name: {}", Thread.currentThread().getName());
        return 1 + 2;
    }
}
